<?php
namespace Home\Controller;
use Think\Controller;
use Think\Log;
use Org\Util\GetPin;
use Home\Common\Wechat;


class WeixinController extends Controller
{

	private $token;
	private $data=array();
	public $fans;
	public $wxuser;
	public $apiServer;
	public $siteUrl;
	public $user;
	public $ali;
	public function index(){
		$this -> siteUrl = C('SITE_URL');

        if (!class_exists('SimpleXMLElement')){
            exit('SimpleXMLElement class not exist');
        }
        if (!function_exists('dom_import_simplexml')){
            exit('dom_import_simplexml function not exist');
        }

        $this -> token = htmlspecialchars($_GET['token']);

        if(!preg_match("/^[0-9a-zA-Z]{3,42}$/", $this -> token)){
            exit('error token');
        }
        $weixin = new Wechat($this -> token, $this -> wxuser);

        $this -> wxuser = S('wxuser_' . $this -> token);
        if (!$this -> wxuser || 1){
            $this -> wxuser = D('Wxuser') -> where(array('token' => $this -> token)) -> find();
            S('wxuser_' . $this -> token, $this -> wxuser);
        }
        $this -> user = M('Users') -> where(array('id' => $this -> wxuser['uid'])) -> find();
        $data = $weixin -> request();
        $this -> data = $weixin -> request();
        $this -> fans = S('fans_' . $this -> token . '_' . $this -> data['FromUserName']);
        if (!$this -> fans || 1){
            $this -> fans = M('Userinfo') -> where(array('token' => $this -> token, 'wecha_id' => $this -> data['FromUserName'])) -> find();
            S('fans_' . $this -> token . '_' . $this -> data['FromUserName'], $this -> fans);
        }


        list($content, $type) = $this -> reply($data);
        $weixin -> response($content, $type);

	}

	private function reply($data){

        if ($this -> wxuser['openphotoprint']){
            $photoPrint = new photoPrint($this -> wxuser, $this -> data['FromUserName']);
        }
        if ($this -> wxuser['openphotoprint'] && $this -> fans['photoprintopen']){
            return $photoPrint -> reply($data);
        }

        if (isset($data['MsgType'])) {

            switch ($data['MsgType']) {
                case 'text':
                    if ($data['Content'] == 'wechat ip') {
                        return array($_SERVER['REMOTE_ADDR'], 'text');
                    }

                    //判断是不是有API操作
                    if($data['Content']){
                        $apiData = M('Api') -> where(array('token' => $this -> token, 'status' => 1, 'noanswer' => 0)) -> select();
                        foreach($apiData as $apiArray){
                            if(!(strpos($data['Content'], $apiArray['keyword']) === FALSE)){
                                $api = $apiArray;
                                break;
                            }
                        }
                        if($api != false){
                            $vo['fromUsername'] = $this -> data['FromUserName'];
                            $vo['Content'] = $this -> data['Content'];
                            $vo['toUsername'] = $this -> token;
                            $api['url'] = $this -> getApiUrl($api['url'], $api['apitoken']);
                            if($api['type'] == 2){
                                if (intval($api['is_colation'])){
                                    $vo['Content'] = trim(str_replace($api['keyword'], '', $vo['Content']));
                                }
                                $apidata = $this -> api_notice_increment($api['url'], $vo, 0, 0);
                                return array($apidata, 'text');
                            }else{
                                $xml = $GLOBALS["HTTP_RAW_POST_DATA"];
                                if (intval($api['is_colation'])){
                                    $xml = str_replace(array($api['keyword'], $api['keyword'] . ' '), '', $xml);
                                }
                                $apidata = $this -> api_notice_increment($api['url'], $xml, 0);
                                header("Content-type: text/xml");
                                exit($apidata);
                                return false;
                            }
                        }
                    }


                    //取消关注时
                    $Pin = new GetPin();
                    $key = $data['Content'];
                    $datafun = explode(',', $this -> fun);
                    $tags = $this -> get_tags($key);
                    $back = explode(',', $tags);

                    foreach($back as $keydata => $data){
                        $string = $Pin -> Pinyin($data);
                        if(in_array($string, $datafun) && $string){
                            if($string == 'fujin'){
                                $this -> recordLastRequest($key);
                            }
                            $this -> requestdata('textnum');
                            unset($back[$keydata]);
                            $thirdApp = new thirdApp();
                            if (in_array($string, $thirdApp -> modules())){
                                eval('$thirdApps=new thirdApp();$return=$thirdApps->' . $string . '($back);');
                            }elseif (method_exists('WeixinController', $string)){
                                eval('$return= $this->' . $string . '($back);');
                            }else{
                            }
                            break;
                        }
                    }

                    break;
                case 'voice':
                    //语音消息接收
                    $data['Content'] = $data['Recognition'];
                    if ($data['Recognition']){
                        $this -> data['Content'] = $data['Recognition'];
                    }else{
                        return $this -> nokeywordApi();
                    }
                    break;
                case 'image':
                    //图片消息接收
                    break;
                case 'event':
                    //事件接收
                    switch ($data['Event']) {
                        case 'CLICK':
                            //点击菜单拉取消息时的事件推送
                            $data['Content'] = $data['EventKey'];
                            $this -> data['Content'] = $data['EventKey'];
                            $key = $this->data['Content'];

                            break;
                        case 'VIEW':
                            //点击菜单跳转链接时的事件推送
                            break;
                        case 'subscribe':
                            if ($this -> wxuser['openphotoprint']){
                                $photoPrint -> initUser();
                            }
                            $this -> behaviordata('follow', '1');
                            $this -> requestdata('follownum');

                            //update wechat unfollow user status,modified by zhenjun, 2015-10-28 10:54
                            M( 'Behavior' )->where( array( /*'fid' => 18, */'token' => $this->token, 'openid' =>  $this->data['FromUserName']/*, 'model' => 'follow'*/ ) )->setField( 'type', 0 );
                            $follow_data = M('reply') -> field('home,keyword,content') -> where(array('token' => $this -> token)) -> find();
                            //扫码关注
                            if($data['EventKey'] == 'SCAN')
                            {
                                 //用户未关注时，进行关注后的事件推送 事件KEY值，qrscene_为前缀，后面为二维码的参数值
                                if(!(strpos($data['EventKey'], 'qrscene_') === FALSE)){
                                    $follow_data['keyword'] = $this -> getRecognition(str_replace('qrscene_', '', $data['EventKey']));
                                    $follow_data['home'] = 1;
                                }
                            }
                            //回复文本，可在此判断回复其它内容。
                            return array(html_entity_decode($follow_data['content']), 'text');

                            break;
                        case 'unsubscribe':
                            //取消关注事件
                            $this -> requestdata('unfollownum');

                            //update wechat unfollow user status,modified by zhenjun, 2015-10-28 10:54
                            M( 'Behavior' )->where( array( /*'fid' => 18,*/ 'token' => $this->token, 'openid' =>  $this->data['FromUserName']/*, 'model' => 'follow'*/ ) )->setField( 'type', -2 );

                            //记录数据统计
                            // $follow_data = M('reply') -> field('home,keyword,content') -> where(array('token' => $this -> token)) -> find();
                            return array(html_entity_decode(''), 'text');
                            break;
                        case 'SCAN':
                            //带参二维码，用户已关注时的事件推送
                            if ($this -> wxuser['openphotoprint']){
                                $photoPrint -> initUser();
                            }
                            $data['Content'] = $this -> getRecognition($data['EventKey']);
                            $this -> data['Content'] = $data['Content'];
                            break;
                        case 'LOCATION':
                            //上报地理位置事件
                            return $this -> nokeywordApi();
                            break;
                        default:
                            # code...
                            break;
                }
                    break;
                case 'video':
                    //视频消息接收
                    break;
                case 'shortvideo ':
                    //小视频消息接收
                    break;
                case 'location':
                    //地理位置消息接收
                    break;
                case 'link':
                    //链接消息接收
                    break;
                default:
                    //其它
                    break;
            }

        }

        if(!empty($return)){
            if(is_array($return)){
                return $return;
            }else{
                return array($return, 'text');
            }
        }else{

            //根据关键字返回消息
            return $this -> keyword($key);
        }
    }

    private function keyword($key){

        switch($key){
        case '帮助': return $this -> help();
            break;
        case 'help': return $this -> help();
            break;
        }

        $like['keyword'] = array('like', '%' . $key . '%');
        $like['precisions'] = 1;
        $like['token'] = $this -> token;
        $data = M('keyword') -> where($like) -> order('id desc') -> find();
        if (!$data){
            $like['keyword'] = array('like', '%' . $key . '%');
            $like['precisions'] = 0;
            $data = M('keyword') -> where($like) -> order('id desc') -> find();
        }

        if($data != false){
            $this -> behaviordata($data['module'], $data['pid']);
            switch($data['module']){
            case 'Text': $this -> requestdata('textnum');
                $info = M($data['module']) -> order('id desc') -> find($data['pid']);
                return array(htmlspecialchars_decode(str_replace('{wechat_id}', $this -> data['FromUserName'], $info['text'])), 'text');
                break;
            case 'Praise': $this -> requestdata('other');
                $Vote = M('Praise') -> where(array('id' => $data['pid'])) -> order('id DESC') -> find();
                //return array(array(array($Vote['title'], '', $Vote['picurl'], $this -> siteUrl . '/index.php?m=Wap&c=Praise&a=index&token=' . $this -> token . '&wecha_id=' . $this -> data['FromUserName'] . '&id=' . $data['pid'] . '')), 'news');
                return array(array(array($Vote['title'], $Vote['info'], $this->siteUrl."/".$Vote['picurl'], $this -> siteUrl . '/index.php?m=Wap&c=Praise&a=index&token=' . $this -> token . '&wecha_id=' . $this -> data['FromUserName'] . '&praise=' . $data['pid'] . '')), 'news');
                break;
            case 'RedPacket':
                $this -> requestdata('other');
                $red_packet = M('redpacket') -> where(array('id' => $data['pid'])) -> order('id DESC') -> find();
                //return array(array(array($Vote['title'], '', $Vote['picurl'], $this -> siteUrl . '/index.php?m=Wap&c=Praise&a=index&token=' . $this -> token . '&wecha_id=' . $this -> data['FromUserName'] . '&id=' . $data['pid'] . '')), 'news');
                return array(array(array($red_packet['title'], $red_packet['desc'], $this->siteUrl."/".$red_packet['picurl'], $this -> siteUrl . '/index.php?m=Wap&c=RedPacket&a=index&token=' . $this -> token . '&wecha_id=' . $this -> data['FromUserName'] . '&id=' . $data['pid'] . '')), 'news');
                break;
            case 'Editor':
                $this -> requestdata('other');
                $editor = M('editor') -> where(array('id' => $data['pid'])) -> order('id DESC') -> find();
                //return array(array(array($Vote['title'], '', $Vote['picurl'], $this -> siteUrl . '/index.php?m=Wap&c=Praise&a=index&token=' . $this -> token . '&wecha_id=' . $this -> data['FromUserName'] . '&id=' . $data['pid'] . '')), 'news');
                return array(array(array($editor['title'], $editor['push_desc'], $this->siteUrl."/".$editor['push_image'], $this -> siteUrl . '/index.php?m=Wap&c=Editor&a=index&token=' . $this -> token . '&wecha_id=' . $this -> data['FromUserName'] . '&id=' . $data['pid'] . '')), 'news');
                break;
            case 'Questionnaire':
                $this -> requestdata('other');
                $questionnaire = M('questionnaire') -> where(array('id' => $data['pid'])) -> order('id DESC') -> find();
                //return array(array(array($Vote['title'], '', $Vote['picurl'], $this -> siteUrl . '/index.php?m=Wap&c=Praise&a=index&token=' . $this -> token . '&wecha_id=' . $this -> data['FromUserName'] . '&id=' . $data['pid'] . '')), 'news');
                return array(array(array($questionnaire['title'], $questionnaire['push_desc'], $this->siteUrl."/".$questionnaire['push_image'], $this -> siteUrl . '/index.php?m=Wap&c=Questionnaire&a=index&token=' . $this -> token . '&wecha_id=' . $this -> data['FromUserName'] . '&id=' . $data['pid'] . '')), 'news');
                break;
            case 'Enroll':
                $this->requestdata('other');
                $Enroll = M('Enroll')->where(array('id' => $data['pid']))->order('id DESC')->find();
                return array(array(array($Enroll['title'], $Enroll['info'], $this->siteUrl."/".$Enroll['headimg'], $this->siteUrl.'/index.php?m=Wap&c=Enroll&a=index'.'&wecha_id='.$this->data['FromUserName'].'&enroll='.$data['pid'] . '')), 'news');
                break;
            case 'Sign':
                $this->requestdata('other');
                $Sign = M('Sign') -> where(array('id' => $data['pid']))->order('id DESC')->find();
                return array(array(array($Sign['conferencename'], $Sign['conferenceinfo'], $this->siteUrl.$Sign['pic'], $this->siteUrl.$Sign['url'])), 'news');
                break;
            case 'Lottery':
                $this->requestdata('other');
                
                $check = D('Wap/lottery')->checkLottery($data['pid']);
            
                if($check['status'] == 0)
                {
                    return array($check['msg'], 'text');
                }
                $item = D('Wap/lottery_item');
                $detail = $item->lotteryResult($data['pid'], $this->data['FromUserName']);
                if($detail == null)
                {
                    return array('系统错误，请重新来过！！', 'text');
                }
                if($detail['success'])
                {
                    
                  
                    return array($detail['item']['name'], 'image');
                    
                  
                }
                else
                {
                    
                    if( $detail['msg'] == '很遗憾，您未中奖，请下次再来!')
                    {
                        return array('6C4FPNrtH__T3CIHolEpmaUKC4nfjeekOVgVfw90RPNKFAOn1LcocZyjcKB9arOg', 'image');
                    }
                    else
                        return array($detail['msg'], 'text');
                }
                
                break;
            default: $replyClassName = $data['module'] . 'Reply';
                if (class_exists($replyClassName)){
                    $replyClass = new $replyClassName($this -> token, $this -> data['FromUserName'], $data, $this -> siteUrl);
                    return $replyClass -> index();
                }else{
                    $this -> requestdata('videonum');
                    $info = M($data['module']) -> order('id desc') -> find($data['pid']);
                    return array(array($info['title'], $info['keyword'], $info['musicurl'], $info['hqmusicurl']), 'music');
                }
            }
        }else{
                $nokeywordReply = $this -> nokeywordApi();
                if ($nokeywordReply){
                    return $nokeywordReply;
                }
                if ($this -> wxuser['transfer_customer_service']){
                    return array('turn on transfer_customer_service', 'transfer_customer_service');
                }
            return array('点击自定义菜单第三栏“小记者”中的“上传作品”可继续上传作品，点击“作品人气榜”可为孩子的作品添人气（即刻起-11月30日17:00）', 'text');

        }
}

private function nokeywordApi(){
    if(!(strpos($this -> fun, 'api') === FALSE)){
        $apiwhere = array('token' => $this -> token, 'status' => 1, 'noanwser' => 1);
        $apiwhere['noanswer'] = array('gt', 0);
        $api = M('Api') -> where($apiwhere) -> find();
        if($api != false){
            $vo['fromUsername'] = $this -> data['FromUserName'];
            $vo['Content'] = $this -> data['Content'];
            if (intval($api['is_colation'])){
                $vo['Content'] = trim(str_replace($api['keyword'], '', $this -> data['Content']));
            }
            $vo['toUsername'] = $this -> token;
            $api['url'] = $this -> getApiUrl($api['url'], $api['apitoken']);
            if($api['type'] == 2){
                $apidata = $this -> api_notice_increment($api['url'], $vo, 0, 0);
                return array($apidata, 'text');
            }else{
                $xml = file_get_contents("php://input");
                if (intval($api['is_colation'])){
                    $xml = str_replace(array($api['keyword'], $api['keyword'] . ' '), '', $xml);
                }
                $apidata = $this -> api_notice_increment($api['url'], $xml, 0);
                if ($apidata != 'false'){
                    header("Content-type: text/xml");
                    exit($apidata);
                    return false;
                }
            }
        }
    }
}
private function getApiUrl($url, $token){
    $timestamp = time();
    $nonce = $_GET["nonce"];
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING);
    $tmpStr = implode($tmpArr);
    $signature = sha1($tmpStr);
    if (strpos($url, '?')){
        $url = $url . '&fromthirdapi=1&signature=' . $signature . '&timestamp=' . $timestamp . '&nonce=' . $nonce . '&apitoken=' . $this -> token;
    }else{
        $url = $url . '?fromthirdapi=1&signature=' . $signature . '&timestamp=' . $timestamp . '&nonce=' . $nonce . '&apitoken=' . $this -> token;
    }
    return $url;
}
private function getFuncLink($u){
    $urlInfos = explode(' ', $u);
    switch ($urlInfos[0]){
    default: $url = str_replace(array('{wechat_id}', '{siteUrl}', '&amp;'), array($this -> data['FromUserName'], $this -> siteUrl, '&'), $urlInfos[0]);
        break;
    case '优惠券': $Lottery = M('Lottery') -> where(array('token' => $this -> token, 'type' => 3, 'status' => 1)) -> order('id DESC') -> find();
        $url = $this -> siteUrl . U('Wap/Coupon/index', array('token' => $this -> token, 'wecha_id' => $this -> data['FromUserName'], 'id' => $Lottery['id']));
        break;
    case '投票': $url = $this -> siteUrl . U('Wap/Vote/index', array('token' => $this -> token, 'wecha_id' => $this -> data['FromUserName'], 'id' => $urlInfos[1]));
        break;
    }
    return $url;
}

//rippletek微路由
private function postJson($url, $jsonData){
    $ch = curl_init($url) ;
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$jsonData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
private function rippleos_auth_url($node) {
    $this->rptk_err_msg = array(
	'数据库错误',
    '请求格式错误',
	'参数不完整',
	'参数类型错误',
	'服务器错误',
	'节点不存在',
	'认证API ID或KEY错误',
	'不存在对应的OPENID'
      );
$date = array('api_id' => C('rptk_wx_auth_api_id'),
        'api_key' => C('rptk_wx_auth_api_key'),
	'node' => intval($node),
	'openid' => $this->data['FromUserName']);
	return json_decode($this->postJson('http://wx.rippletek.com/Portal/Wx/get_auth_url', json_encode($date)), true);
}
private function rippleos_auth_token($node) {
	$this->rptk_err_msg = array(
	'数据库错误',
	'请求格式错误',
	'参数不完整',
	'参数类型错误',
	'服务器错误',
	'节点不存在',
	'认证API ID或KEY错误',
	'不存在对应的OPENID'
         );
$date = array('api_id' => C('rptk_wx_auth_api_id'),
	'api_key' => C('rptk_wx_auth_api_key'),
	'node' => intval($node),
	'openid' => $this->data['FromUserName']);
        return json_decode($this->postJson('http://wx.rippletek.com/Portal/Wx/get_auth_token', json_encode($date)), true);
}
private function rippleos_unauth($node) {
	$date = array('api_id' => C('rptk_wx_auth_api_id'),
	'api_key' => C('rptk_wx_auth_api_key'),
	'node' => intval($node),
	'openid' => $this->data['FromUserName']);
	$ret = json_decode($this->postJson('http://wx.rippletek.com/Portal/Wx/unauth_user', json_encode($date)), true);
	return;
}

private function recordLastRequest($key, $msgtype = 'text'){
    $rdata = array();
    $rdata['time'] = time();
    $rdata['token'] = $this -> _get('token');
    $rdata['keyword'] = $key;
    $rdata['msgtype'] = $msgtype;
    $rdata['uid'] = $this -> data['FromUserName'];
    $user_request_model = M('User_request');
    $user_request_row = $user_request_model -> where(array('token' => $this -> _get('token'), 'msgtype' => $msgtype, 'uid' => $rdata['uid'])) -> find();
    if(!$user_request_row){
        $user_request_model -> add($rdata);
    }else{
        $rid['id'] = $user_request_row['id'];
        $user_request_model -> where($rid) -> save($rdata);
    }
}


//帮助
private function help(){
    $this -> behaviordata('help', '', '1');
    $data = M('reply') -> where(array('token' => $this -> token)) -> find();
    if (!$data || !$data['content']){
        $data = array('content' => '恭喜您，接入成功');
    }
    return array(preg_replace("/(\015\012)|(\015)|(\012)/", "\n", $data['content']), 'text');
}

private function error_msg($data){
    return '没有找到' . $data . '相关的数据';
}


/*
*记录请求信息统计
*field 字段名
*/
private function requestdata($field){
    $data['year'] = date('Y');
    $data['month'] = date('m');
    $data['day'] = date('d');
    $data['token'] = $this -> token;
    $mysql = M('Requestdata');
    $check = $mysql -> field('id') -> where($data) -> find();
    if($check == false){
        $data['time'] = time();
        $data[$field] = 1;
        $mysql -> add($data);

    }else{
        $mysql -> where($data) -> setInc($field);
    }
}

private function behaviordata($field, $id = '', $type = ''){
    $data['date'] = date('Y-m-d', time());
    $data['token'] = $this -> token;
    $data['openid'] = $this -> data['FromUserName'];
    $data['keyword'] = $this -> data['Content'];
    if (!$data['keyword']){
        $data['keyword'] = '用户关注';
    }
    $data['model'] = $field;
    if($id != false){
        $data['fid'] = $id;
    }
    if($type != false){
        $data['type'] = 1;
    }else{
        $data['type'] = 0;
    }

    $mysql = M('Behavior');
    $check = $mysql -> field('id') -> where($data) -> find();

    if($check == false){

        $data['num'] = 1;
        $data['enddate'] = time();

        $mysql -> add($data);


    }else{
        $mysql -> where($data) -> setInc('num');
    }
}

//获取带参数二维码的数据
private function getRecognition($id){
    $GetDb = D('Recognition');
    $data = $GetDb -> field('keyword') -> where(array('id' => $id, 'status' => 0)) -> find();
    if($data != false){
        $GetDb -> where(array('id' => $id)) -> setInc('attention_num');
        return $data['keyword'];
    }else{
        return false;
    }
}

//关键词触发第三方接口
private function api_notice_increment($url, $data, $converturl = 1){
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    if ($converturl){
        if (strpos($url, '?')){
            $url .= '&token=' . $this->token.'&Content='.$this->data['Content'].'&FromUserName='.$this->data['FromUserName'].'&ToUsername='.$this->data['ToUsername'];
        }else{
            $url .= '?token=' . $this->token.'&Content='.$this->data['Content'].'&FromUserName='.$this->data['FromUserName'].'&ToUsername='.$this->data['ToUsername'];
        }
    }
    $headers = array("User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1", "Accept-Language: en-us,en;q=0.5", "Referer:http://mp.weixin.qq.com/", 'Content-type: text/xml');
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSLVERSION, 3);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)){
        return false;
    }else{
        return $tmpInfo;
    }
}

private function adddUserInfo(){
    $access_token = $this -> _getAccessToken();
    $url2 = 'https://api.weixin.qq.com/cgi-bin/user/info?openid=' . $this -> data['FromUserName'] . '&access_token=' . $access_token;
    $classData = json_decode($this -> curlGet($url2));
    $db = M('wechat_group_list');
    $data['token'] = $this -> token;
    $data['openid'] = $this -> data['FromUserName'];
    $item = $db -> where(array('token' => $this -> token, 'openid' => $this -> data['FromUserName'])) -> find();
    $data['nickname'] = str_replace("'", '', $classData -> nickname);
    $data['sex'] = $classData -> sex;
    $data['city'] = $classData -> city;
    $data['province'] = $classData -> province;
    $data['headimgurl'] = $classData -> headimgurl;
    $data['subscribe_time'] = $classData -> subscribe_time;
    $url3 = 'https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=' . $access_token;
    $json2 = json_decode($this -> curlGet($url3, 'post', '{"openid":"' . $data['openid'] . '"}'));
    $data['g_id'] = $json -> groupid;
    if (!$data['g_id']){
        $data['g_id'] = 0;
    }
    if (!$item){
        $db -> data($data) -> add();
    }else{
        $db -> where(array('token' => $this -> token, 'openid' => $this -> data['FromUserName'])) -> save($data);
    }
}
private function _getAccessToken(){
    //manage access token in cache, modified by zhenjun, 2015-10-29 15:40
    $where = array('token' => $this -> token);
    $this -> thisWxUser = M('Wxuser') -> where($where) -> find();
    $access_token = S( 'access_token_'.$this->thisWxUser['token'] );
    if( !$access_token ){
        $url_get = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this -> thisWxUser['appid'] . '&secret=' . $this -> thisWxUser['appsecret'];
        $json = json_decode($this -> curlGet($url_get));
        if (!$json -> errmsg){
            $access_token = $json -> access_token;
            S( 'access_token_'.$this->thisWxUser['token'], $access_token, 6300 );
        }else{
            $this -> error('获取access_token发生错误：错误代码' . $json -> errcode . ',微信返回错误信息：' . $json -> errmsg);
        }

    }
    return $access_token;
}
private function curlGet($url, $method = 'get', $data = ''){
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    return $temp;
}
private function get_tags($title, $num = 10){
    vendor('Pscws.Pscws4', '', '.class.php');
    $pscws = new \PSCWS4();
    $pscws -> set_dict(CONF_PATH . 'etc/dict.utf8.xdb');
    $pscws -> set_rule(CONF_PATH . 'etc/rules.utf8.ini');
    $pscws -> set_ignore(true);
    $pscws -> send_text($title);
    $words = $pscws -> get_tops($num);
    $pscws -> close();
    $tags = array();
    foreach ($words as $val){
        $tags[] = $val['word'];
    }
    return implode(',', $tags);
}

public function handleIntro($str){
    $str = html_entity_decode(htmlspecialchars_decode($str));
    $search = array('&amp;', '&quot;', '&nbsp;', '&gt;', '&lt;');
    $replace = array('&', '"', ' ', '>', '<');
    return strip_tags(str_replace($search, $replace, $str));
}

}
?>
